﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using Castle.ActiveRecord;
using Castle.ActiveRecord.Framework.Config;
using CosyTrade.Core;
using CosyTrade.Data;

namespace CosyTrade.Network.WebServicesPortal
{
    public class Global : System.Web.HttpApplication
    {
        readonly AddinServices services = AddinServices.Instance;
        protected void Application_Start(object sender, EventArgs e)
        {
            services.InitalizeAddin();
            InitOrm(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "dbConfig.xml"));
            services.StartAddin();

            Application["AddinServices"] = services;
        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {

        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {
            services.Stop();
        }

        static void InitOrm(string defaultDbConfigPath)
        {
            Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
            List<Type> regTypes = new List<Type>();
            foreach (Assembly assembly in assemblies)
            {
                try
                {
                    Type[] assemblyTypes = assembly.GetTypes();
                    foreach (Type assemblyType in assemblyTypes)
                    {
                        if (assemblyType.IsDefined(typeof (ActiveRecordAttribute), false) &&
                            !assemblyType.IsDefined(typeof (NotAutoRegister), false))
                            regTypes.Add(assemblyType);
                    }
                }
                catch (Exception ex)
                {
                    using (StreamWriter sw =
                        new StreamWriter(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Log.txt"), true,
                                         Encoding.UTF8))
                    {
                        sw.WriteLine(assembly.FullName);
                        sw.WriteLine(ex.Message);
                        sw.WriteLine(ex.StackTrace);
                        throw;
                    }

                }
            }
            XmlConfigurationSource source = new XmlConfigurationSource(defaultDbConfigPath);
            ActiveRecordStarter.Initialize(source, regTypes.ToArray());
        }
    }
}